package com.student.liu.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.student.liu.entity.Goods;
import com.student.liu.entity.ShopCar;
import com.student.liu.service.IShopCarService;
import lombok.Data;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Map;

@RestController
@RequestMapping("shop")
public class ShopCarController extends BaseController{

    @Resource
    IShopCarService shopCarService;
    /**
     * 加入购物车
     * @param shopCar
     * @return
     */
    @PostMapping("create")
    public Object create(@RequestBody ShopCar shopCar) {
        shopCarService.addShopCar(shopCar);
        return success("加入购物车成功", null);
    }

    @PostMapping("page")
    @SentinelResource(
            value = "goodsPage",            // 用于定义资源名称
            fallback = "pageFallback"       // 用于定义失败之后的降级处理
    )
    public Object page(@Valid @RequestBody ShopCarController.GoodsPageBody goodsPageBody, BindingResult result) throws InterruptedException {
        Integer userId = Integer.parseInt(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        IPage<Map<String, Object>> goodsMaps = shopCarService.shopCarPage(goodsPageBody.getPageIndex(), 15);
        return success("", goodsMaps);
    }

    /**
     * page 接口请求失败后的降级处理
     * @param goodsPageBody
     * @param result
     * @return
     */
    public Object pageFallback(@Valid @RequestBody ShopCarController.GoodsPageBody goodsPageBody, BindingResult result) {
        return fail("请求失败，请稍后重试！", 429);
    }

    /**
     * 修改购物车商品数量
     *
     * @return
     */
    @PostMapping("setInventory")
    public Object putOn(@Valid @RequestBody ShopCarController.ShopCarBody shopCarBody,BindingResult result) {
        shopCarService.setInventory(shopCarBody.id,shopCarBody.inventory);
        return success("修改成功", null);
    }

    @PostMapping("remove")
    public Object remove(@RequestBody ShopCar shopCar) {
        shopCarService.removeShopCar(shopCar.getId());
        return success("删除购物车成功", null);
    }

    /**
     * 商品分页查询参数实体
     */
    @Data
    static class GoodsPageBody {
        @NotNull(message = "请传递页码")
        private Integer pageIndex;
    }

    /**
     * 购物车分页查询参数实体
     */
    @Data
    static class ShopCarBody {
        @NotNull(message = "购物车商品ID")
        private Integer id;
        @NotNull(message = "修改的数量")
        private Short inventory;
    }
}
